/**
 * @date 4:40:49 PM
 * ControllerExceptionHandler.java
 * Administrator
 * TODO
 */
package com.qs.education.bean.exception;


import org.apache.log4j.Logger;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import com.qs.education.bean.utils.JsonUtil;


/**
 * @class ControllerExceptionHandler
 * @author Brooks
 * @description 
 * @date Oct 23, 2018
 */
@RestControllerAdvice
public class ControllerExceptionHandler {
	private final Logger log = Logger.getLogger(this.getClass());
	/**
     * 所有异常报错
     * @param request
     * @param exception
     * @return
     * @throws Exception
     */
	@ExceptionHandler(Exception.class)
    public String defaultErrorHandler(Exception e)
    {
        log.info("handleException");
        ResultCode r = new ResultCode();
        if (e instanceof org.springframework.web.servlet.NoHandlerFoundException)
        {
            r.put("code", 404);
            r.put("msg", "page not found");
        } else
        {
            log.error(e.getMessage(), e);
            r.put("code", 500);
            r.put("msg", e.getMessage());
        }
        return JsonUtil.beanToJson(r);
    }

    
    /**
     * 处理自定义异常,需要创建异常类
     */
    /*@ExceptionHandler(HHException.class)
    public ResultCode handleHWException(HHException e)
    {
        log.info("handleHHException");
        ResultCode r = new ResultCode();
        r.put("code", e.getCode());
        r.put("msg", e.getMessage());
        return r;
    }*/

    
    @ExceptionHandler(DuplicateKeyException.class)
    public ResultCode handleDuplicateKeyException(DuplicateKeyException e)
    {
        log.info("handleDuplicateKeyException");
        log.error(e.getMessage(), e);
        return ResultCode.error("数据库中已存在该记录");
    }
    
    
    @ExceptionHandler(UnauthorizedException.class)
    public ModelAndView handleDuplicateKeyException(UnauthorizedException e)
    {
        ModelAndView mv = new ModelAndView("noPrivilege");
        return mv;
    }
    


}
